﻿using LY.Common.Utils;
using LY.Common.Utils.Sf_Struct;
using LY.Common.Utils.Sign;
using LY.Entity;
using LY.Entity.Jsons;
using LY.Entity.PageSearch;
using LY.Interface;
using QJ.CMS.Filters;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace QJ.CMS.Controllers
{
    [MyAuthorization]
    public class UserOrderController : Controller
    {
        //
        // GET: /UserOrder/
        private IProjectItemService _projectItemService;
        private IUserAddressService _userAddressService;
        private IProjectService _project;
        private IMemberService _member;
        private IFundsFlowService _fservice;

        private static string _sftAddress = ConfigurationManager.AppSettings["SftAddress"];
        private static string _merchantNo = ConfigurationManager.AppSettings["merchantNo"];
        //
        private static string _zFmysenderId = ConfigurationManager.AppSettings["ZFmysenderId"];
        private static string _zFKey = ConfigurationManager.AppSettings["ZFKey"];

        private static string _backAddress = ConfigurationManager.AppSettings["BackAddress"];
        private static string _apiAddress = ConfigurationManager.AppSettings["ApiAddress"];
        public UserOrderController(IProjectItemService projectItemService, IUserAddressService userAddressService, IProjectService project, IMemberService member, IFundsFlowService fservice)
        {
            _projectItemService = projectItemService;
            _userAddressService = userAddressService;
            _project = project;
            _member = member;
            _fservice = fservice;
        }

        //添加订单
        public ActionResult AddOrder(int itemid, int? ProjectId, int id = 0)
        {
            U_Member member = (U_Member)Session["CurrentUser"];
            if (member == null)
            {
                return RedirectToAction("Index", "Login");
            }

            if (ProjectId != null)
            {
                R_Project pro = _project.GetProject(ProjectId);
                if (pro == null)
                {
                    return RedirectToAction("Error", "Default");
                }
                ViewBag.ProjectName = pro.ProjectName;
            }
            else
            {
                ViewBag.ProjectName = Server.UrlDecode(Request["projectName"]);
            }
            if (id != 0)
            {
                R_ProjectOrder projectOrder = _project.GetProjectOrder(id);
                if (projectOrder == null)
                {
                    return RedirectToAction("Error", "Default");
                }
                //获取备注信息
                ViewBag.remark = projectOrder.Remark;
                //获取发票状态
                ViewBag.NeedInvoice = projectOrder.NeedInvoice;
                ViewBag.Id = projectOrder.Id;
            }
            //获取购买的档位信息
            R_ProjectItem item = _projectItemService.GetProjectItem(itemid);

            //获取默认收件地址
            ViewBag.Address = _userAddressService.GetDefaultAddress(member.ID);
            //获取所有的地址
            ViewBag.MemberAddresses = _userAddressService.QueryMemberAddresses(member.ID);


            if (item == null)
            {
                return RedirectToAction("Error", "Default");
            }
            return View(item);
        }

        //保存订单
        public ActionResult SaveOrder()
        {
            U_Member member = (U_Member)Session["CurrentUser"];
            if (member == null)
            {
                return RedirectToAction("Index", "Login");
            }
            R_ProjectOrder order = new R_ProjectOrder();
            int addressId = int.Parse(Request["AddressId"]);

            //运费Freight
            int Freight = int.Parse(Request["Freight"]);

            if (Request["nicai"] != null)
            {
                addressId = int.Parse(Request["nicai"]);
            }
            U_UserAddress address1 = _userAddressService.GetAddress(addressId);
            if (Request["Id"] != "0")
            {
                order.Id = int.Parse(Request["Id"]);
            }
            order.ProjectId = int.Parse(Request["ProjectId"]);
            order.ProjectItemId = int.Parse(Request["ProjectItemId"]);
            order.Amount = decimal.Parse(Request["Amount"]);
            order.MemberId = member.ID;
            order.AddTime = DateTime.Now;
            //order.SerialNumber = "默认序列号";//在添加订单的时候就把序列号生成好
            order.SerialNumber = "quanju" + DateTime.Now.ToString("yyMMddHHmmss") + new Random().Next(0, 99999);
            order.Contacts = address1.Name;
            order.ContactNumber = address1.Tel;
            order.Remark = Request["Remark"];
            order.PayStatus = 0;
            order.NeedInvoice = int.Parse(Request["NeedInvoice"]);
            if (Request["NeedInvoice"] != "0")
            {
                order.InvoiceTitle = Request["InvoiceTitle"];
            }

            order.UserAddress = address1.Address;
            order.ItemFreight = Freight;//运费Freight

            int result = _project.SaveProjectOrder(order);//新增一个订单
            if (result > 0)
            {
                int _orderId = 0;
                if (Request["Id"] != "0")
                {
                    _orderId = int.Parse(Request["Id"]);//编辑
                }
                else
                {
                    _orderId = result;//新增
                }
                return RedirectToAction("OrderConfirm", new
                {
                    projectName = Request["projectName"],
                    orderId = _orderId,
                    contacts = order.Contacts,
                    address = address1.Address,
                    phone = order.ContactNumber,
                    remark = order.Remark,
                    itemId = order.ProjectItemId,
                    serialNumber = order.SerialNumber,
                    sign = 1
                });
            }
            else
            {
                return null;
            }
        }

        //确认订单
        public ActionResult OrderConfirm(string serialNumber)
        {
            ViewBag.zFmysenderId = _zFmysenderId;
            //收货地址
            //ViewBag.address = Request["address"];
            if (Request["sign"] != null)
            {
                ViewBag.sign = Request["sign"];
            }

            //订单信息
            R_ProjectOrder order = _project.GerProjectOrderBySerialNumber(serialNumber);
            if (order == null)
            {
                return RedirectToAction("Error", "Default");
            }
            else
            {
                //项目详情
                R_Project project1 = _project.GetProject(order.ProjectId);
                //回报详情
                R_ProjectItem projectItem = _projectItemService.GetProjectItem(order.ProjectItemId);
                //会员信息
                //U_Member member1 = _member.getMemberInfo(project1.MemberId);
                ViewBag.projectId = project1.Id;
                ViewBag.projectName = project1.ProjectName;
                ViewBag.orderId = order.Id;
                ViewBag.contacts = order.Contacts;
                ViewBag.address = order.UserAddress;
                ViewBag.phone = order.ContactNumber;
                ViewBag.remark = order.Remark;
                ViewBag.serialNumber = order.SerialNumber;
                ViewBag.NeedInvoice = order.NeedInvoice;
                ViewBag.InvoiceTitle = order.InvoiceTitle;
                //int itemId = int.Parse(Request["itemId"]);
                // R_ProjectItem item = _projectItemService.GetProjectItem(itemId);
                // R_Project project = _project.GetProject(item.ProjectId);
                ViewBag.BiaoNo = project1.BiaoNo;
                U_Member member = (U_Member)Session["CurrentUser"];
                ViewBag.item = projectItem;
                ViewBag.memberName = member.Name;
                ViewBag.SFTUserName = member.SFTUserName;
                ViewBag.agreeWithhold = "2"; //先默认没卡自动投标
                ViewBag.availableAmount = "0";
                ViewBag.sftAddress = _sftAddress;
                ViewBag.merchantNo = _merchantNo;
                ViewBag.backAddress = _backAddress;

                if (!string.IsNullOrEmpty(member.SFTUserName))
                {
                    Dictionary<string, string> dic = GetBalance();
                    ViewBag.agreeWithhold = dic["agreeWithhold"];
                    ViewBag.availableAmount = dic["availableAmount"];
                }
                string ip = "";
                if (Request.ServerVariables["HTTP_VIA"] != null)
                {
                    ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
                }
                else
                {
                    ip = Request.ServerVariables["REMOTE_ADDR"].ToString();
                }
                ViewBag.BuyerIp = ip;
                return View();
            }
        }

        //投标添加空的资金流
        public ActionResult AddTouBiaoFundsFlow()
        {
            MySign mysign = new MySign();
            string strOrigin = Request["sign"];
            Array array = strOrigin.Split('|');
            string time = DateTime.Now.ToString("yyyyMMddHHmmss");
            Array.Sort(array);
            string tmp = "";
            for (int i = 0; i < array.Length; i++)
            {
                if (((string[])(array))[i].Contains("timestamp"))//替换时间
                {
                    ((string[])(array))[i] = ((string[])(array))[i].Replace("temp", time);
                }
                //if (((string[])(array))[i].Contains("submitBidNo"))//替换投标的编号
                //{
                //    string order = time.Substring(2, 12);
                //    ((string[])(array))[i] = ((string[])(array))[i].Replace("orderNum", order);
                //}
                tmp += ((string[])(array))[i] + "&";
            }
            tmp = tmp.Substring(0, tmp.Length - 1);

            //添加资金流
            U_FundsFlow fundsFlow = new U_FundsFlow();
            fundsFlow.OrderNo = Request["orderNo"];
            U_Member member = (U_Member)Session["CurrentUser"];
            fundsFlow.MemberId = member.ID;
            fundsFlow.OutPay = decimal.Parse(Request["amount"]);
            fundsFlow.CreateTime = DateTime.Now;
            fundsFlow.Status = 0;
            fundsFlow.Type = 3;
            fundsFlow.ProjectId = int.Parse(Request["projectId"]);
            int j = _fservice.BiaoFundsFlow(fundsFlow);
            return Content(time + mysign.GetSign(tmp));
        }

        #region 订单详情
        public ActionResult OrderDetail(string SerialNumber)
        {
            //订单信息
            R_ProjectOrder projectOrder = _project.GerProjectOrderBySerialNumber(SerialNumber);
            if (projectOrder == null)
            {
                return RedirectToAction("Error", "Default");
            }
            else
            {
                //项目详情
                R_Project project = _project.GetProject(projectOrder.ProjectId);
                //回报详情
                R_ProjectItem projectItem = _projectItemService.GetProjectItem(projectOrder.ProjectItemId);
                //会员信息
                U_Member member = _member.getMemberInfo(project.MemberId);

                //收货地址
                ViewBag.UserAddress = projectOrder.UserAddress;
                ViewBag.ContactNumber = projectOrder.ContactNumber;
                ViewBag.SerialNumber = SerialNumber;
                ViewBag.Amount = projectOrder.Amount;
                ViewBag.Remark = projectOrder.Remark;
                ViewBag.memberName = member.Name;
                ViewBag.MRedoundContent = projectItem.MRedoundContent;
                ViewBag.projectName = project.ProjectName;
                //ViewBag.Amount = projectOrder.Amount;
                ViewBag.Freight = projectItem.Freight;
                ViewBag.PayStatus = projectOrder.PayStatus;
            }

            return View();

        }
        //取消订单
        public JsonResult CancelOrder(string orderid)
        {
            JsonSMsg msg = new JsonSMsg();
            //取消订单 修改支付状态为交易关闭2
            int ret = _project.UpdateOrderPayStatus(10, orderid);
            if (ret > 0)
            {
                msg.Status = 1;
                msg.Message = "操作成功";
            }
            else
            {
                msg.Status = -1;
                msg.Message = "操作失败";
            }
            return Json(msg);
        }

        //删除订单
        public JsonResult DeleteOrder(string orderid)
        {
            JsonSMsg msg = new JsonSMsg();
            int ret = _project.DeleteOrder(orderid);
            if (ret > 0)
            {
                msg.Status = 1;
                msg.Message = "操作成功";
            }
            else
            {
                msg.Status = -1;
                msg.Message = "操作失败";
            }
            return Json(msg);
        }

        //申请退款
        public ActionResult Refund()
        {
            R_ProjectOrder projectOrder = _project.GerProjectOrderBySerialNumber(Request["orderNo"]);
            if (projectOrder==null)
            {
                return Content("订单处理失败");
            }
            projectOrder.PayStatus = 5;
            int i = _project.SaveProjectOrder(projectOrder);
            if (i > 0)
            {
                return Content("订单处理成功");
            }
            else
            {
                return Content("订单处理失败");
            }
        }
        #endregion

        #region 查询余额 和 是否开启自动投标
        //查询余额和是否开通自动投标
        public Dictionary<string, string> GetBalance()
        {
            U_Member member = (U_Member)Session["CurrentUser"];
            //盛付通接口应改成 member.SFTUserName; QJ13818609394
            string userName = member.SFTUserName; //"quanju_" + member.Name;
            string sign = "merchantNo=" + _merchantNo + "&userName=" + userName;
            MySign mysign = new MySign();
            string temp = mysign.GetSign(sign);
            string newsign = Server.UrlEncode(temp);
            WebClient webClient = new WebClient();
            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            string postString = "?sign=" + newsign;
            string url = _apiAddress + "/userAccount/" + _merchantNo + "-" + userName + postString;
            byte[] postData = Encoding.ASCII.GetBytes(postString);
            byte[] responseData = webClient.DownloadData(url);
            string strJson = Encoding.UTF8.GetString(responseData);
            //验证返回数据
            JavaScriptSerializer js = new JavaScriptSerializer();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            Type type = typeof(Dictionary<string, string>);
            dic = (Dictionary<string, string>)js.Deserialize(strJson, type);
            List<string> test = new List<string>(dic.Keys);
            test.Remove("sign");
            string[] queryString = new string[test.Count];
            for (int i = 0; i < test.Count; i++)
            {
                queryString[i] = test[i] + "=" + dic[test[i]];
            }
            Array array = queryString;
            Array.Sort(array);
            queryString = (string[])array;
            string hehe = string.Join("&", queryString);
            bool result = mysign.ValidateSign(hehe, dic["sign"]);
            if (result)
            {
                return dic;
            }
            else
            {
                return null;
            }
        }
        #endregion

        //自动投标
        public ActionResult ZiDongTouBiao()
        {
            //添加资金流
            U_FundsFlow fundsFlow = new U_FundsFlow();
            fundsFlow.OrderNo = Request["submitBidNo"];
            U_Member member = (U_Member)Session["CurrentUser"];
            fundsFlow.MemberId = member.ID;
            fundsFlow.OutPay = decimal.Parse(Request["creditAmount"]);
            fundsFlow.CreateTime = DateTime.Now;
            fundsFlow.Status = 0;
            fundsFlow.Type = 3;
            fundsFlow.ProjectId = int.Parse(Request["projectId"]);
            int j = _fservice.BiaoFundsFlow(fundsFlow);

            string creditAmount = Request["creditAmount"];
            string creditUserName = member.SFTUserName;
            string discountAmount = "0.00";
            string issueBidNo = Request["issueBidNo"];
            string merchantNo = _merchantNo;
            string notifyUrl = _backAddress + "/Pay/OrderConfirmApiNotifyUrl";
            string submitBidNo = Request["submitBidNo"];
            string sign = "creditAmount=" + creditAmount + "&creditUserName=" + member.SFTUserName +
                          "&discountAmount=0.00" + "&issueBidNo=" + issueBidNo + "&merchantNo=" + _merchantNo + "&notifyUrl=" + _backAddress + "/Pay/OrderConfirmApiNotifyUrl" +
                          "&submitBidNo=" + submitBidNo;
            MySign mysign = new MySign();
            string temp = mysign.GetSign(sign);
            string newsign = Server.UrlEncode(temp);
            /*
            WebClient webClient = new WebClient();
            webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header，如果改为GET方式的话就去掉这句话即可  
            //string postString = "?creditAmount=" + creditAmount + "&creditUserName=" + creditUserName + "&discountAmount=" + discountAmount + 
            //    "&notifyUrl=" + notifyUrl +"&submitBidNo=" + submitBidNo + "&sign=" + temp;
            string postString = "?creditAmount=" + creditAmount + "&creditUserName=" + creditUserName + "&discountAmount=" + discountAmount +
                  "&issueBidNo=" + issueBidNo + "&merchantNo=" + merchantNo + "&notifyUrl=" + notifyUrl + "&submitBidNo=" + submitBidNo + 
                  "&sign=" + temp;
            byte[] postData = Encoding.UTF8.GetBytes(postString);//编码，尤其是汉字，事先要看下抓取网页的编码方式
            string url = "http://wdtest.shengpay.com/api/p2pBid/" + merchantNo + "-" + issueBidNo + "/submitBid";
            byte[] responseData = webClient.UploadData(url, "POST", postData);//得到返回字符流 
            //byte[] responseData = webClient.DownloadData(url);
            string strJson = Encoding.UTF8.GetString(responseData);
            return Content(strJson);
            */
            WebClient wc = new WebClient();
            StringBuilder postData = new StringBuilder();
            postData.Append("creditAmount=" + creditAmount);
            postData.Append("&creditUserName=" + creditUserName);
            postData.Append("&discountAmount=" + discountAmount);
            postData.Append("&issueBidNo=" + issueBidNo);
            postData.Append("&merchantNo=" + merchantNo);
            postData.Append("&notifyUrl=" + notifyUrl);
            postData.Append("&submitBidNo=" + submitBidNo);
            postData.Append("&sign=" + newsign);
            byte[] sendData = Encoding.UTF8.GetBytes(postData.ToString());
            wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            wc.Headers.Add("ContentLength", sendData.Length.ToString());
            string url = _apiAddress + "/p2pBid/" + merchantNo + "-" + issueBidNo + "/submitBid";
            byte[] recData = wc.UploadData(url, "POST", sendData);
            string strJson = Encoding.UTF8.GetString(recData);
            //验证返回数据
            JavaScriptSerializer js = new JavaScriptSerializer();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            Type type = typeof(Dictionary<string, string>);
            dic = (Dictionary<string, string>)js.Deserialize(strJson, type);
            List<string> test = new List<string>(dic.Keys);
            test.Remove("sign");
            string[] queryString = new string[test.Count];
            for (int i = 0; i < test.Count; i++)
            {
                queryString[i] = test[i] + "=" + dic[test[i]];
            }
            Array array = queryString;
            Array.Sort(array);
            queryString = (string[])array;
            string hehe = string.Join("&", queryString);
            bool result = mysign.ValidateSign(hehe, dic["sign"]);
            if (result)
            {
                return Content("true");
            }
            else
            {
                return Content("false");
            }
        }

        //自动投标的同步响应页面
        public ActionResult ZiDongTouBiaoCallBack()
        {
            if (Request["result"] == "true")
            {
                ViewBag.hehe = "验证数据正确";
            }
            else
            {
                ViewBag.hehe = "验证数据失败";
            }
            return View("OrderConfirmCallBack");
        }

        //众筹支付新接口，纯粹的支付接口
        public ActionResult AddZhiFuFundsFlow()
        {
            string time = DateTime.Now.ToString("yyyyMMddHHmmss");
            //先根据传过来的金额查询是不是正确的,防止使用js修改金额。
            R_ProjectOrder order = _project.GerProjectOrderBySerialNumber(Request["orderNo"]);
            if ((order.Amount + order.ItemFreight).ToString()!= Request["amount"])
            {
                return Content(time + "hehe");
            }
            //添加资金流
            U_FundsFlow fundsFlow = new U_FundsFlow();
            fundsFlow.OrderNo = Request["orderNo"];
            U_Member member = (U_Member)Session["CurrentUser"];
            fundsFlow.MemberId = member.ID;
            fundsFlow.OutPay = decimal.Parse(Request["amount"]);
            fundsFlow.CreateTime = DateTime.Now;
            fundsFlow.Status = 0;
            fundsFlow.Type = 3;
            fundsFlow.ProjectId = int.Parse(Request["projectId"]);
            int j = _fservice.BiaoFundsFlow(fundsFlow);
            string originalSign = Request["sign"];
            originalSign = originalSign.Replace("OrderTime", time);
            string signMsg = MD5Util.GetMD5_32(originalSign + _zFKey).ToUpper();
            MyLog.WriteLog("众筹投资订单", originalSign + "|||||_-_-_-_-_-||||||" + _zFKey);
            return Content(time + signMsg);
        }

        //众筹支付新接口同步的返回
        [MyAuthorization(IsLoginValidate = "false")]
        public ActionResult OrderConfirmCallBack()
        {
            MyLog.Write("众筹支付新接口同步的返回");
            MyLog.Write(Request["TransStatus"]);
            string orderNo = Request["OrderNo"];
            string TraceNo = Request["TraceNo"]; //请求序列号 报文发起方唯一消息标识
            string transNo = Request["TransNo"]; //盛付通交易号
            string BankSerialNo = Request["BankSerialNo"];//网银流水号
            string transStatus = Request["TransStatus"];

            MyLog.WriteLog("众筹支付新接口同步的返回", orderNo+","+Request["TransStatus"]+","+TraceNo+","+transNo+","+BankSerialNo);

            if (Request["TransStatus"] == "01")
            {
                ViewBag.hehe = "支付成功";
            }
            else
            {
                ViewBag.hehe = "处理中";
            }
            try 
            {

            }
            catch (Exception ex)
            {
                throw ex;
            }
            return View();
        }
    }
}
